/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.images;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import org.jsoup.Jsoup;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: jse2204 - QrcodeDemo
 * <p>Powered by webrx On 2022-09-26 17:15:50
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class QrcodeDemo {
    public static void main(String[] args) throws Exception {
        //生成二维码
        //String url = "https://gd-hbimg.huaban.com/b8c200d3c9e0298e2965940a5dffdf8adbe7e5c1816716-Lu07gf_fw658";
        //var bm = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, 200, 200);
        //var i = MatrixToImageWriter.toBufferedImage(bm);
        //ImageIO.write(i, "png", new FileOutputStream("qr.png"));
        //Runtime.getRuntime().exec("cmd /k start qr.png");

        //encode("tel://13014577033",200,200,"me.png");
        //encode("http://www.baidu.com",200,200,"baidu.jpg");


        //System.out.println(decode("c:/b.png"));

        String w = JOptionPane.showInputDialog("请输入词汇：");
        String u = "https://cn.bing.com/dict/search?q=" + w;
        String t = Jsoup.connect(u).get().select("span[class=def b_regtxt]").get(0).text();

        encode(w + ":\r\n" + t, 200, 200, w + ".jpg");

        JOptionPane.showMessageDialog(null, t);


    }

    public static String decode(String filename) {
        String str = null;
        try {
            var img = ImageIO.read(new File(filename));
            var src = new BufferedImageLuminanceSource(img);
            var binarizer = new HybridBinarizer(src);
            var binaryBitmap = new BinaryBitmap(binarizer);
            var result = new QRCodeReader().decode(binaryBitmap);
            str = result.getText();
        } catch (Exception e) {

        }
        return str;
    }


    public static void encode(String text, int width, int height, String filename) {
        try {
            String url = text;
            Map<EncodeHintType,String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
            var bm = new QRCodeWriter().encode(url, BarcodeFormat.QR_CODE, width, height,hints);
            var i = MatrixToImageWriter.toBufferedImage(bm);
            ImageIO.write(i, filename.substring(filename.lastIndexOf(".") + 1), new FileOutputStream(filename));
            Runtime.getRuntime().exec("cmd /k start " + filename);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
